﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO; 

// 写入版本
public class AndroidAutoBuilderEditor : EditorWindow {
	const int GUI_GAP = 20;
	bool _isCheckedTencent = false;
    bool _isCheckedMeizu = false;

	#region Main
	[MenuItem ("WZLZ/AndroidAutoBuilder")]
	// Add menu item to show this demo.
	static void Init() {
		EditorWindow.GetWindow(typeof(AndroidAutoBuilderEditor));
	}

	void OnGUI() {
		var check = EditorGUILayout.Toggle("Tencent 应用宝", _isCheckedTencent);
		if (check != _isCheckedTencent){
			_isCheckedTencent = check;
			if (_isCheckedTencent){
				Debug.Log("Checke");
			}else{
				Debug.Log("UnChecke");
			}
		}

		if (GUILayout.Button("Build And Run - Tencent 应用宝")){
			BuildAndRunTencent();
        }

	   GUILayout.Space(GUI_GAP);

	 	check = EditorGUILayout.Toggle("Meizu 魅族", _isCheckedMeizu);
		if (check != _isCheckedMeizu){
			_isCheckedMeizu = check;
			if (_isCheckedMeizu){
				Debug.Log("Checke");
			}else{
				Debug.Log("UnChecke");
			}
		}

		GUILayout.Space(GUI_GAP);

        if (GUILayout.Button("Batch Build")){
			AutoBuild();
        }

 		if (GUILayout.Button("Test Set Icon")){
			test();
        }
	}

    #endregion

	#region Auto Build
	// 按照在UI界面中选择的渠道，来进行编译
	public void AutoBuild(){
		if (_isCheckedTencent){
			PrepareTencent();
		}
	}

	// 把渠道信息写入wzlzBuildInfo文件中
	public void writeToFile(string channel){
        string strEditorPath = Application.dataPath; //<path to project folder>/Assets
		string filePath = strEditorPath + "/Resources/wzlzBuildInfo.json";

        try
        {
			Hashtable jsonTable = null;
			if (File.Exists(filePath)){
		        TextAsset asset = Resources.Load("wzlzBuildInfo") as TextAsset;
		        string strFlieData = asset.text;
				jsonTable = MiniJsonExtensions.hashtableFromJson(strFlieData);
				
				// 读出文件内容后，删除文件				
				File.Delete(filePath);
			}else{
				jsonTable = new Hashtable();
			}

			jsonTable["Channel"] = channel;		
			string strJson = MiniJsonExtensions.toJson(jsonTable);

			// 写入文件
            StreamWriter sw;          
            FileInfo t = new FileInfo(filePath);
            sw = t.CreateText();
            sw.WriteLine(strJson);
            sw.Close();
            sw.Dispose();
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
        }
    }
	#endregion

	#region Tencent
	public void BuildAndRunTencent(){
		PrepareTencent();
		buildAndRun("Tencent");
	}

	public void PrepareTencent(){
		// 拷贝所需文件到Plugin下
		var sourcePath = Application.dataPath + "/../../WZLZAndroidChannelPlugin/release/tencentPlugin";
		var desPath = Application.dataPath + "/Plugins/Android";
		CopyAndReplaceDirectory(sourcePath, desPath);		

		//  设置so文件
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi/libBugly.so");
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi/liblbs.so");
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi/libYSDK.so");
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi-v7a/libBugly.so");
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi-v7a/liblbs.so");
		setSoLibAsPlugin("Assets/Plugins/Android/libs/armeabi-v7a/libYSDK.so");

		// 设置出包的名字
		PlayerSettings.applicationIdentifier = "com.tentap.wzlz.tencent";

		// 设置APP名字
		PlayerSettings.productName = "应用宝_测试demo";

		// 设置Icon: 在Resources目录下
		string path = "Icon/Tencent/icon";
		SetDefaultIcon.DoSetIcon(path);

		// 设置SplashScene: 注：只能用替换的方式，目前不支持编程方式
		
		// 写入buildInfo文件		
		writeToFile("tencent");
	}

	#endregion

	#region Helper
	void test(){
		// 设置Icon
		string path = "Icon/Tencent/icon";
		SetDefaultIcon.DoSetIcon(path);



		buildAndRun("test");
	}		

//	void OnInspectorUpdate()
//    {
//		Debug.Log("OnInspectorUpdate");
////        Repaint();
//    }


	void setSoLibAsPlugin(string path){
		((PluginImporter)PluginImporter.GetAtPath(path)).SetCompatibleWithPlatform(BuildTarget.Android, true);
	}

	void buildAndRun(string channel){
		BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.scenes = new[] { "Assets/Scenes/Android/AndroidChannelDemo.unity"};
        buildPlayerOptions.locationPathName = "AndroidTest_" + channel + ".apk";
        buildPlayerOptions.target = BuildTarget.Android;
        buildPlayerOptions.options = BuildOptions.AutoRunPlayer;
        BuildPipeline.BuildPlayer(buildPlayerOptions);
	}

	public void CopyAndReplaceDirectory(string srcPath, string dstPath, bool isOverwrite = true)
	{
//		Debug.Log("TTP CopyAndReplaceDirectory: " + srcPath + " to: " + dstPath);

		if (Directory.Exists(dstPath) && isOverwrite)
			Directory.Delete(dstPath, true);
		if (File.Exists(dstPath) && isOverwrite)
			File.Delete(dstPath);
	
		if (!Directory.Exists(dstPath) && !File.Exists(dstPath)){
			Directory.CreateDirectory(dstPath);
		}
		
		foreach (var file in Directory.GetFiles(srcPath)){
			if (file.EndsWith(".meta")){
				continue;
			}
			string desPath = Path.Combine(dstPath, Path.GetFileName(file));
//			Debug.Log("TTP Copy: " + file + " to: " + desPath);
			File.Copy(file, desPath);
		}
			

		foreach (var dir in Directory.GetDirectories(srcPath)){
			if (dir.EndsWith(".meta")){
				continue;
			}
			CopyAndReplaceDirectory(dir, Path.Combine(dstPath, Path.GetFileName(dir)));
		}
	}
	#endregion


}
